package com.heima.search.service.impl;

import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * ClassName: ApUserSearchServiceImpl
 * Description:
 * date: 2023/8/19 0019 16:05
 *
 * @author zHan
 */

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索记录
     *
     * @param keyWord
     * @param userId
     */
    @Override
    @Async
    public void insertSearch(String keyWord, Integer userId) {
        // 查询当前用户的搜索关键词
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("keyword").is(keyWord));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        // 判断是否存在
        // 存在，更新时间
        if (apUserSearch != null) {
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }
        // 判断关键词条数是否大于10
        Query queryList = Query.query(Criteria.where("userId").is(userId));
        // 如果大于10，删除最后一条数据
        List<ApUserSearch> apUserSearchList =
                mongoTemplate.find(queryList.with(Sort.by(Sort.Direction.DESC, "createdTime")),
                        ApUserSearch.class);

        if (apUserSearchList.size() >= 10) {
            ApUserSearch userSearch = apUserSearchList.get(apUserSearchList.size() - 1);
            mongoTemplate.remove(userSearch);
        }
        // 保存数据
        apUserSearch = new ApUserSearch();
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(keyWord);
        apUserSearch.setCreatedTime(new Date());
        mongoTemplate.save(apUserSearch);
    }

    /**
     * 加载用户历史记录
     *
     * @return
     */
    @Override
    public ResponseResult loadSearch() {
        // 查询用户消息
        ApUser apUser = AppThreadLocalUtil.getUser();
        // 用户未登录
        if (apUser == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 查询
        Query query = Query.query(Criteria.where("userId").is(apUser.getId()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> apUserSearchList =
                mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearchList);
    }

    /**
     * 删除用户历史记录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult deleteSearch(HistorySearchDto dto) {
        // 检查参数
        if (dto.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 查询用户消息
        ApUser apUser = AppThreadLocalUtil.getUser();
        // 用户未登录
        if (apUser == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 查询删除
        Query query = Query.query(Criteria.where("id").is(dto.getId())
                .and("userId").is(apUser.getId()));
        mongoTemplate.remove(query, ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
